<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,200分)- 找单词（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给一个字符串和一个二维字符数组&#xff0c;如果该字符串存在于该数组中&#xff0c;则按字符串的字符顺序输出字符串每个字符所在单元格的位置下标字符串&#xff0c;如果找不到返回字符串“N”。</p> 
<p>1.需要按照字符串的字符组成顺序搜索&#xff0c;且搜索到的位置必须是相邻单元格&#xff0c;其中“相邻单元格”是指那些水平相邻或垂直相邻的单元格。</p> 
<p>2.同一个单元格内的字母不允许被重复使用。</p> 
<p>3.假定在数组中最多只存在一个可能的匹配。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第1行为一个数字N指示二维数组在后续输入所占的行数。</p> 
<p>第2行到第N&#43;1行输入为一个二维大写字符数组&#xff0c;每行字符用半角,分割。</p> 
<p>第N&#43;2行为待查找的字符串&#xff0c;由大写字符组成。</p> 
<p>二维数组的大小为N*N&#xff0c;0&lt;N&lt;&#61;100。</p> 
<p>单词长度K&#xff0c;0&lt;K&lt;1000。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出一个位置下标字符串&#xff0c;拼接格式为&#xff1a;第1个字符行下标&#43;”,”&#43;第1个字符列下标&#43;”,”&#43;第2个字符行下标&#43;”,”&#43;第2个字符列下标… &#43;”,”&#43;第N个字符行下标&#43;”,”&#43;第N个字符列下标。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">4<br /> A,C,C,F<br /> C,D,E,D<br /> B,E,S,S<br /> F,E,C,A<br /> ACCESS</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">0,0,0,1,0,2,1,2,2,2,2,3</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">ACCESS分别对应二维数组的[0,0] [0,1] [0,2] [1,2] [2,2] [2,3]下标位置。</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题和<a href="https://blog.csdn.net/qfc_128220/article/details/127711035?spm&#61;1001.2014.3001.5501" title="华为机试 - 单词搜索_伏城之外的博客-CSDN博客">华为机试 - 单词搜索_伏城之外的博客-CSDN博客</a></p> 
<p>很像。只是本题在上面这题的基础上&#xff0c;要求保存路径坐标。</p> 
<p></p> 
<p>题目假定在数组中最多只存在一个可能的匹配。因此我们只要找到即返回。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const path &#61; require(&#34;path&#34;);
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; parseInt(lines[0]);
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 2) {
    lines.shift();
    const str &#61; lines.pop();

    const grid &#61; lines.map((line) &#61;&gt; line.split(&#34;,&#34;));

    console.log(findLetter(grid, n, str));

    lines.length &#61; 0;
  }
});

function findLetter(grid, n, str) {
  function dfs(i, j, k, path) {
    if (i &lt; 0 || i &gt;&#61; n || j &lt; 0 || j &gt;&#61; n || grid[i][j] !&#61;&#61; str[k])
      return false;

    path.push([i, j]);
    if (path.length &#61;&#61;&#61; str.length) return true;

    const tmp &#61; grid[i][j];
    grid[i][j] &#61; undefined;

    const res &#61;
      dfs(i - 1, j, k &#43; 1, path) ||
      dfs(i &#43; 1, j, k &#43; 1, path) ||
      dfs(i, j - 1, k &#43; 1, path) ||
      dfs(i, j &#43; 1, k &#43; 1, path);

    if (!res) {
      grid[i][j] &#61; tmp;
      path.pop();
    }

    return res;
  }

  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    for (let j &#61; 0; j &lt; n; j&#43;&#43;) {
      const path &#61; [];
      if (dfs(i, j, 0, path)) {
        return path.toString();
      }
    }
  }

  return &#34;N&#34;;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringJoiner;

public class Main {
  static int n;
  static String[][] matrix;
  static String tar;

  public static void main(String[] args) {
    // 将输入分隔符改为“,”和换行
    Scanner sc &#61; new Scanner(System.in).useDelimiter(&#34;[,\n]&#34;);

    n &#61; sc.nextInt();

    matrix &#61; new String[n][n];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; n; j&#43;&#43;) {
        matrix[i][j] &#61; sc.next();
      }
    }

    tar &#61; sc.next();

    System.out.println(getResult());
  }

  public static String getResult() {
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; n; j&#43;&#43;) {
        LinkedList&lt;Integer[]&gt; path &#61; new LinkedList&lt;&gt;();
        if (dfs(i, j, 0, path)) {
          StringJoiner sj &#61; new StringJoiner(&#34;,&#34;);
          for (Integer[] pos : path) sj.add(pos[0] &#43; &#34;,&#34; &#43; pos[1]);
          return sj.toString();
        }
      }
    }
    return &#34;N&#34;;
  }

  public static boolean dfs(int i, int j, int k, LinkedList&lt;Integer[]&gt; path) {
    if (i &lt; 0 || i &gt;&#61; n || j &lt; 0 || j &gt;&#61; n || !tar.substring(k, k &#43; 1).equals(matrix[i][j])) {
      return false;
    }

    path.add(new Integer[] {i, j});
    if (path.size() &#61;&#61; tar.length()) return true;

    String tmp &#61; matrix[i][j];
    matrix[i][j] &#61; null;

    boolean res &#61;
        dfs(i - 1, j, k &#43; 1, path)
            || dfs(i &#43; 1, j, k &#43; 1, path)
            || dfs(i, j - 1, k &#43; 1, path)
            || dfs(i, j &#43; 1, k &#43; 1, path);

    if (!res) {
      matrix[i][j] &#61; tmp;
      path.removeLast();
    }

    return res;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
matrix &#61; [input().split(&#34;,&#34;) for _ in range(n)]
tar &#61; input()


def dfs(i, j, k, path):
    if i &lt; 0 or i &gt;&#61; n or j &lt; 0 or j &gt;&#61; n or matrix[i][j] !&#61; tar[k]:
        return False

    path.append([i, j])
    if len(path) &#61;&#61; len(tar):
        return True

    tmp &#61; matrix[i][j]
    matrix[i][j] &#61; &#34;&#34;

    res &#61; dfs(i - 1, j, k &#43; 1, path) or dfs(i &#43; 1, j, k &#43; 1, path) or dfs(i, j - 1, k &#43; 1, path) or dfs(i, j &#43; 1, k &#43; 1, path)

    if not res:
        matrix[i][j] &#61; tmp
        path.pop()

    return res


# 算法入口
def getReuslt():
    for i in range(n):
        for j in range(n):
            path &#61; []
            if dfs(i, j, 0, path):
                return &#34;,&#34;.join(map(lambda x: &#34;,&#34;.join(map(str, x)), path))

    return &#34;N&#34;


# 算法调用
print(getReuslt())
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>